package com.elanfox.littlereporter.controller;

import com.elanfox.littlereporter.common.ExcelHelper;
import com.elanfox.littlereporter.common.GradeType;
import com.elanfox.littlereporter.common.StringUtilsExt;
import com.elanfox.littlereporter.dto.ContributionDTO;
import com.elanfox.littlereporter.entity.ContributionPO;
import com.elanfox.littlereporter.model.ContributionSearchCondition;
import com.elanfox.littlereporter.service.ContributionService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;


/**
 * @author allan
 * @date 2018-03-25
 */
@Controller
public class ContributionController {
    @Autowired
    private ContributionService contributionService;
    @Autowired
    private Environment environment;
    private static final String[] TH = {
            "小记者名称",
            "小记者证号",
            "所在学校",
            "所在班级",
            "标题",
            "内容"
    };

    @RequestMapping(value = "/bList", method = RequestMethod.GET)
    public String bList(
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            @ModelAttribute("condition") ContributionSearchCondition searchCondition,
            Model model
    ) throws UnsupportedEncodingException {
        Page<ContributionPO> contributionPOS = contributionService.findAll(pageIndex, 20, searchCondition);
        for (ContributionPO p : contributionPOS) {
            p.setCreateTimeFormat(StringUtilsExt.dateFormat(p.getCreateTime(), StringUtilsExt.TIME_PATTERN));
            p.setContent(URLDecoder.decode(p.getContent(), "utf-8"));
        }
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", contributionPOS.getTotalElements());
        model.addAttribute("totalPages", contributionPOS.getTotalPages());
        model.addAttribute("contributions", contributionPOS.getContent());
        model.addAttribute("gradeTypes", GradeType.values());

        return "b_contributions_list";
    }

    @RequestMapping(value = "/fList", method = RequestMethod.GET)
    public String fList(
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            @ModelAttribute("condition") ContributionSearchCondition searchCondition,
            Model model
    ) throws UnsupportedEncodingException {
        Page<ContributionPO> contributionPOS = contributionService.findAll(pageIndex, 10, searchCondition);

        for (ContributionPO p : contributionPOS) {
            p.setCreateTimeFormat(StringUtilsExt.dateFormat(p.getCreateTime(), "yyyy/MM/dd"));
            p.setContent(URLDecoder.decode(p.getContent(), "utf-8"));
        }

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", contributionPOS.getTotalElements());
        model.addAttribute("totalPages", contributionPOS.getTotalPages());
        model.addAttribute("contributions", contributionPOS.getContent());

        return "f_contributions_list";
    }

    @RequestMapping("/export")
    @ResponseBody
    public void export(int pageIndex, ContributionSearchCondition condition, HttpServletResponse response) throws IOException {
        Page<ContributionPO> contributionPOS = contributionService.findAll(pageIndex, 10, condition);
        HSSFWorkbook workbook = ExcelHelper.createWorkbook();

        for (ContributionPO contributionPO : contributionPOS) {
            List<List<ExcelHelper.CellDesc>> rowAndCells = new ArrayList<>();

            List<ExcelHelper.CellDesc> row = new ArrayList<>();
            row.add(ExcelHelper.asCell(contributionPO.getReporterName()));
            row.add(ExcelHelper.asCell(contributionPO.getReporterNum()));
            row.add(ExcelHelper.asCell(contributionPO.getSchool()));
            row.add(ExcelHelper.asCell(contributionPO.getClassName()));
            row.add(ExcelHelper.asCell(contributionPO.getTitle()));
            row.add(ExcelHelper.asCell(URLDecoder.decode(contributionPO.getContent(), StringUtilsExt.ENCODING_UTF8)));
            rowAndCells.add(row);

            ExcelHelper.createSheet(workbook, contributionPO.getTitle(), TH, rowAndCells);
        }

        //输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=" + StringUtilsExt.dateFormat(new Date(), StringUtilsExt.TIME_PATTERN_WITH_NO_SEG) + ".xls");
        response.setContentType("application/msexcel");
        workbook.write(output);
        output.flush();
        output.close();
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(
            int pageIndex,
            ContributionSearchCondition searchCondition
    ) throws UnsupportedEncodingException {
        Page<ContributionPO> contributionPOS = contributionService.findAll(pageIndex, 10, searchCondition);
        for (ContributionPO p : contributionPOS) {
            p.setCreateTimeFormat(StringUtilsExt.dateFormat(p.getCreateTime(), "yyyy/MM/dd"));
            p.setContent(URLDecoder.decode(p.getContent(), "utf-8"));
        }
        contributionPOS.getContent().forEach(p -> p.setCreateTimeFormat(StringUtilsExt.dateFormat(p.getCreateTime(), "yyyy/MM/dd")));
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", pageIndex);
        map.put("totalRecords", contributionPOS.getTotalElements());
        map.put("totalPages", contributionPOS.getTotalPages());
        map.put("contributions", contributionPOS.getContent());

        return map;
    }

    @RequestMapping(value = "/submit", method = RequestMethod.GET)
    public String submit(Model model) {
        model.addAttribute("gradeTypes", GradeType.values());

        return "f_submit";
    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public int submit(
            ContributionDTO contributionDTO
    ) {
        ContributionPO contributionPO = contributionDTO.toPO();
        contributionService.save(contributionPO);

        return 1;
    }

    @RequestMapping(value = "/bDetail", method = RequestMethod.GET)
    public String bDetail(int id, Model model) throws UnsupportedEncodingException {
        ContributionPO p = contributionService.findById(id);
        p.setCreateTimeFormat(StringUtilsExt.dateFormat(p.getCreateTime(), "yyyy/MM/dd"));
        p.setContent(URLDecoder.decode(p.getContent(), "utf-8"));
        model.addAttribute("contribution", p);

        return "b_detail";
    }

    @RequestMapping(value = "/fDetail", method = RequestMethod.GET)
    public String fDetail(int id, Model model) throws UnsupportedEncodingException {
        ContributionPO p = contributionService.findById(id);
        p.setCreateTimeFormat(StringUtilsExt.dateFormat(p.getCreateTime(), "yyyy/MM/dd"));
        p.setContent(URLDecoder.decode(p.getContent(), "utf-8"));
        model.addAttribute("contribution", p);

        return "f_detail";
    }
}
